package com.yzzrjy.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {

    // 私钥
    private static String SECRET = "yzzrjy";

    // 有效期七天
    private static long time = 7 * 24 * 3600 * 1000;

    // HS256算法
    private static Algorithm algorithm = Algorithm.HMAC256(SECRET);

    // 签发token
    public static String getToken(String uid) {
        try {
            Map<String, Object> headerClaims = new HashMap();
            headerClaims.put("alg", "HS256");
            headerClaims.put("type", "JWT");

            JWTCreator.Builder builder = JWT.create();
            builder.withHeader(headerClaims);
            if (uid != null) {
                builder.withClaim("uid", uid); // 用户信息
            }
            String token = builder.withExpiresAt(new Date(System.currentTimeMillis() + time)) // 有效期截止
                    .sign(algorithm); // 加密
            return token;
        } catch (JWTCreationException e) {
            return null;
        }

    }

    // 验证token
    public static boolean verifyToken(String uid, String token) {
        try {
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 执行验证
            DecodedJWT jwt = verifier.verify(token);
            // 获取令牌中定义的声明
            Map<String, Claim> claims = jwt.getClaims();
            // 返回指定键映射到的值
            String uid1 = claims.get("uid").asString();
            if(uid.equals(uid1)){
                return true;
            }
            return false;
        } catch (JWTVerificationException e) {
            return false;
        }
    }
}
